<template>
  <PageLayout backRouteName="index" navTitle="组件示例" routeMethod="pushTab">
    <div ref="domRef" class="page-container">
      <!-- 表格标题栏：新增“全屏切换”按钮 -->
      <div class="table-header">

        <BasicTable @register="registerTable" :rowSelection="rowSelection" @expand="onExpand" >
          <!--插槽:table标题-->
          <template #tableTitle>
            <a-button type="primary" v-auth="'dw:dw_pro_plan:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增订单</a-button>
            <a-button  type="primary" v-auth="'dw:dw_pro_plan:exportXls'" preIcon="ant-design:export-outlined" @click="handleParentExport"> 导出</a-button>
            <j-upload-button type="primary" v-auth="'dw:dw_pro_plan:importExcel'" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
            <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button v-auth="'dw:dw_pro_plan:deleteBatch'">批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
            </a-dropdown>
            <!-- 高级查询 -->
            <super-query :config="superQueryConfig" @search="handleSuperQuery"  v-auth="'dw:dw_pro_plan:add'" />



            <a-button type="warning" v-auth="'dw:dw_pro_plan:add'" @click="handleOnEx" preIcon="ant-design:plus-outlined"  style="margin-left: auto;"> 生产计划报表</a-button>
            <a-button
              type="primary"
              @click="toggleDom"
              class="mr-2"

            >
              {{ isFullscreen ? '退出全屏' : '全屏表格' }}
            </a-button>
          </template>
          <!--操作栏-->
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
          </template>
          <template #expandedRowRender="{ record }"  >
            <a-button type="primary" v-auth="'dw:dw_assemble:add'" @click="childHandleAdd(record)" preIcon="ant-design:plus-outlined"> 新增工序</a-button>
            <a-dropdown v-if="selectedRowKeyss.length > 0"  >
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button v-auth="'dw:dw_assemble:deleteBatch'">批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
            </a-dropdown>
            <BasicTable @register="registerInnerTable" :rowSelection="rowSelection12"   :searchInfo={record}>
              <!--操作栏-->
              <template #action="{ record }">

                <!--操作栏-->
                <TableAction :actions="getchildTableAction(record)" :dropDownActions="getChildDropDownAction(record)"/>
              </template>


            </BasicTable>
          </template>

          <!--字段回显插槽-->
          <template v-slot:bodyCell="{ column, record, index, text }">
          </template>


        </BasicTable>
      </div>
      <!-- 表单区域 -->
      <DwProPlanModal @register="registerModal" @success="handleSuccess"       ></DwProPlanModal>
      <DwAssembleModal @register="registerDwAssembleModal" @success="handleSuccessChild"></DwAssembleModal>
    </div>
  </PageLayout>
</template>

<script lang="ts" name="dw-dwProPlan" setup>
import { usePermission } from '/@/hooks/web/usePermission';
import {ref, reactive, onMounted, onUnmounted} from 'vue';
import {BasicTable, TableAction} from '/@/components/Table';
import {useModal} from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import DwProPlanModal from './components/DwProPlanModal.vue'
import {columns,searchFormSchema, superQuerySchema} from './DwProPlan.data';
import {innerColumns} from './DwAssemble.data';
// 导入权限钩子
import {
  list,
  childlist,
  deleteOne,
  batchDelete,
  getImportUrl,
  getExportUrl,
  deleteOneChild
} from './DwProPlan.api';
import DwAssembleModal from "@/views/dw/components/DwAssembleModal.vue";
import { useFullscreen } from '@vueuse/core';
// 1. 定义导出全局配置（列表页和弹窗页共享）
const parentExportConfig = ref({
  url: getExportUrl(false), // 默认列表接口
  params: {},               // 存储导出参数
  name: "生产计划"          // 默认文件名
});
// 2. 弹窗专用临时配置（仅在弹窗导出时使用）
// const childExportConfig = ref({
//   url: getExportUrl(true),  // 弹窗专属接口（报表导出）
//   params: {},               // 弹窗参数（如月份）
//   name: "生产计划报表"      // 弹窗导出文件名
// });
// 3. 列表查询参数（父页面导出时使用）
const queryParam = reactive<any>({});

//注册model
const [registerModal,{openModal}] = useModal();
// 注册子表model
const [registerDwAssembleModal, { openModal: openDwAssembleModal }] = useModal();
//5. 册table数据  // 初始化列表页：绑定父页面默认配置
const {tableContext,onExportXls,onImportXls } = useListPage({
  tableProps:{
    title: '生产计划',
    api: list,
    columns,
    striped:true,
    canResize:false,
    scroll: { y: 1000 },
    expandRowByClick: true,
    pagination:{
      pageSize:50,

    },

    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter:true,
      showAdvancedButton:true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
        ['orderDate', ['orderDate_begin', 'orderDate_end'], 'YYYY-MM-DD'],
        ['checkout', ['checkout_begin', 'checkout_end'], 'YYYY-MM-DD'],

      ],
    },
    actionColumn: {
      width: 120,
      fixed:'right'
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },

  },
  exportConfig: parentExportConfig.value,
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})
// 6. 解构表格上下文（确保类型正确）
const [registerTable,{reload},{ rowSelection, selectedRowKeys }] = tableContext

// 7. 子表初始化（不变）
const { tableContext: transactionTable } = useListPage({
  tableProps: {
    title: '',
    api: childlist,
    columns:innerColumns,
    canResize: false,
    useSearchForm: false,
    pagination:false,
    expandRowByClick: true,
    striped:true,
    beforeFetch: (params) => {
      // console.log("params---->",params)
      // let aa = {id:params.record.id,ct:params.record.createTime}
      let param = {proPlanId:params.record.id}
      return Object.assign(params, param);
    },
  },

});


const [registerInnerTable,{reload:reload1},{ rowSelection:rowSelection12, selectedRowKeys:selectedRowKeyss }] = transactionTable;
// 8. 高级查询配置（不变）
const superQueryConfig = reactive(superQuerySchema);
// 11. 父页面导出方法：强制使用父页面配置（核心修复）
const handleParentExport = () => {
  const listPageExportConfig = (tableContext as any).exportConfig;
  if (listPageExportConfig) {
    // 重置为父页面默认配置（接口 + 查询参数）
    Object.assign(listPageExportConfig, {
      ...parentExportConfig.value,
      params: queryParam, // 携带父页面当前查询条件
    });
  }
  // 执行导出
  onExportXls();
};
// 12. 弹窗类型标记（控制关闭时是否重置）
const modalType = ref('');
// 13. 打开弹窗：标记类型为onEx
const handleOnEx = () => {
  modalType.value = 'onEx';
  openModal(true, { isUpdate: false, showFooter: true, type: "onEx" });
};


/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}
/**
 * 新增事件
 */
function handleAdd() {
  modalType.value = 'add';
  openModal(true, {
    isUpdate: false,
    showFooter: true,
    type: "add",
  });
}



/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
    type: "edit",
  });
}

/**
 * 详情
 */
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({id: record.id}, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 操作栏
 */
function getTableAction(record){
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      auth: 'dw:dw_pro_plan:edit'
    }
  ]
}
/**
 * 下拉操作栏
 */
function getDropDownAction(record){
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }, {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft',
      },
      auth: 'dw:dw_pro_plan:delete'
    }
  ]
}
/*************************************************************子操作栏*******************************************************/
function getchildTableAction(record){
  return [
    {
      label: '编辑',
      onClick: childHandleEdit.bind(null, record),
      // auth: 'dw:dw_pro_plan:edit'
    }
  ]
}
/**
 * 子编辑事件
 */
function childHandleEdit(record: Recordable) {
  openDwAssembleModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 子新增事件
 */
function childHandleAdd(record: Recordable) {
  openDwAssembleModal(true, {
    record:{proPlanId:record.id},
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 子详情
 */
function childHandleDetail(record: Recordable) {
  openDwAssembleModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 子删除事件
 */
async function childHandleDelete(record) {
  await deleteOneChild({id: record.id}, handleSuccessChild);
}
/**
 * 下拉操作栏
 */
function getChildDropDownAction(record){
  return [
    {
      label: '详情',
      onClick: childHandleDetail.bind(null, record),
    }, {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: childHandleDelete.bind(null, record),
        placement: 'topLeft',
      },
      auth: 'dw:dw_pro_plan:delete'
    }
  ]
}

/**
 * 成功回调
 */
function handleSuccessChild() {
  // console.log("sssssss:")
  (selectedRowKeyss.value = []) && reload1() && reload();
}

async function onExpand( ) {
  handleSuccessChild();
}
/** ******************************************************/

// 12. 自动刷新（按权限控制）
  // let intervalId = null;
let intervalId: NodeJS.Timeout | null = null;
const { hasPermission } = usePermission();

const refreshList = async () => {
  try {
    await reload();
    console.log('生产计划列表已自动刷新');
  } catch (error) {
    console.error('自动刷新失败:', error);
  }
};

// 生命周期：挂载时启动自动刷新，卸载时清除
onMounted(() => {
  if (hasPermission('dw:dw_pro_plan:refresh')) {
    intervalId = setInterval(refreshList, 300000); // 每300秒刷新一次
  }
});
onUnmounted(() => {
  if (intervalId) clearInterval(intervalId);
});
/** ******************************************************/

const domRef = ref<Nullable<HTMLElement>>(null); // 绑定需要全屏的DOM
const { toggle: toggleDom, isFullscreen } = useFullscreen(domRef); // 局部全屏（指定DOM）


</script>

<style lang="less" scoped>
:deep(.ant-picker),:deep(.ant-input-number){
  width: 100%;
}
</style>
